package cn.devcat.sso.service.impl;

import cn.devcat.sso.entity.DevcatNote;
import cn.devcat.sso.entity.NoteText;
import cn.devcat.sso.mapper.NoteTextMapper;
import cn.devcat.sso.service.IDevcatNoteService;
import cn.devcat.sso.service.INoteTextService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NoteTextServiceImpl extends ServiceImpl<NoteTextMapper, NoteText> implements INoteTextService {

  @Autowired
  IDevcatNoteService noteService;

  @Override
  public void addNoteText(NoteText text) {
    String pictureUrl = getPictureUrl(text.getContent());
    if (pictureUrl != null) {
      noteService.update(new UpdateWrapper<DevcatNote>().eq("id", text.getId()).set("cover_image", pictureUrl));
    }
    saveOrUpdate(text);
  }

  @Override
  public String getNoteText(Long id) {
    NoteText noteText = getById(id);
    return noteText.getContent();
  }

  @Override
  public void refreshCoverImage() {
    for (NoteText noteText : list()) {
      String pictureUrl = getPictureUrl(noteText.getContent());
      if (pictureUrl != null) {
        noteService.update(new UpdateWrapper<DevcatNote>().eq("id", noteText.getId()).set("cover_image", pictureUrl));
      }
    }
  }


  private String getPictureUrl(String text) {
    if (text.contains("![")) {
      int startIndex = 0;
      int endIndex = 0;
      int tempIndex = text.indexOf("![");
      for (int i = tempIndex; i < text.length(); i++) {
        if (text.charAt(i) == '(') {
          startIndex = i + 1;
        } else if (text.charAt(i) == ')') {
          endIndex = i;
          break;
        }
      }
      return text.substring(startIndex, endIndex);
    }
    return null;
  }
}
